<?php 
/**
 * Created on 2008-3-22
 * 基础代码类
 * @author jctr<jc@cdrj.net.cn>
 * ChengDu CandorSoft Co., Ltd.
 * @version $Id: BaseCode.class.php,v 1.1 2012/02/07 08:59:18 gfl Exp $
 */
namespace Crm\Common;

class MetaData {

    protected $di;

    /**
     * ado连接。
     *
     * @var object
     * @access pdo
     */
    public $pdo;

	/**
     * 构造函数
     * @access public 
     * @param 
     */
    function __construct(){
        $this->di = \PhalApi\DI();
        $this->pdo = $this->di->pdo;
	}

    /**
     * 以键值对的形式取出基础代码
     * @param int $code_type 基础代码类型
     * @param string $where 补充条件
     * @param int $type 1返回key=>value键值对,2返回vaule=>value键值对
     * @access public
     * @return array 返回数组
     */
    public function getPairBaseCodeByType($code_type, $where = " order by sort desc",$type='true')
    {
        $aCode = $this->pdo->find(
            DB_PREFIX_SYS."metadata",
            "flag=1 AND active=1 AND parent_code=".$code_type . " ".$where,
            "code, name"
        );
        $rtn = array();
        for ($i=0, $m=sizeof($aCode); $i < $m; $i++){
            if($type) {
                $rtn[$aCode[$i]['code']] = $aCode[$i]['name'];
            }else{
                //$rtn[$aCode[$i]['name']] = $aCode[$i]['name'];
                $rtn[$i]['key'] = $aCode[$i]['code'];
                $rtn[$i]['value'] = $aCode[$i]['name'];
            }
        }
        return $rtn;
    }

    /**
     * 转换为对象key-value
     */
    public function toKeyValue($data){
        $rlt = array();
        $i=0;
        foreach ($data as $key=>$val){
            $rlt[$i]['key'] = $key;
            $rlt[$i]['value'] = $val;
            $i++;
        }
        return $rlt;
    }


    /**
     * 根据关联代码找出对应基础代码
     * @param int $code_type 基础代码类型
     * @param int $code_type 补充条件
     * @access public
     * @return array 返回数组
     */
    public function getPairBaseCodeByRelateType($code_type, $where = " order by sort desc")
    {
        $aCode = $this->pdo->find(
            DB_PREFIX_SYS."metadata",
            "flag=1 AND relate_code=".$code_type . " ".$where,
            "code, name"
        );
        $rtn = array();
        for ($i=0, $m=sizeof($aCode); $i < $m; $i++) $rtn[$aCode[$i]['code']] = $aCode[$i]['name'];
        return $rtn;
    }

    /**
     * 根据基础代码查询代码名称
     * @access public
     * @param  $code  基础代码
     * @return array
     */
    public function getNameByCode($code) {
        $codes = explode(",", $code);
        if(count($codes)>1){
            $name = '';
            foreach ($codes as $item) {
                $sql = "SELECT id,code,name FROM %s WHERE code = %d AND flag = 1 ";
                $sql = sprintf($sql, DB_PREFIX_SYS . "metadata", $item);
                $arrcode = $this->pdo->getRow($sql);
                $name .= $arrcode['name'].',';
            }
            $name = substr($name,0,-1);
        }else{
            $sql = "SELECT id,code,name FROM %s WHERE code = %d AND flag = 1 ";
            $sql = sprintf($sql, DB_PREFIX_SYS."metadata", $codes[0]);
            $arrcode = $this->pdo->getRow($sql);
            $name = $arrcode['name'];
        }
        return $name;
    }

    /**
     * 根据code获取内容值
     * @access public
     * @param
     * @return
     */
    public function getInfoByCode($code)
    {
        $info = $this->pdo->find(DB_PREFIX_SYS.'metadata','flag = 1 and code = '.$code,'code,name');
        return $info[0];
    }

    /**
     * 根据名称、code获取内容值
     * @access public
     * @param $type array返回数组
     * @return
     */
    public function selectBaseCodeByName($name,$code,$type='')
    {
        $aCode = $this->pdo->find(
            DB_PREFIX_SYS."metadata",
            "flag=1 AND active=1 AND parent_code=".$code." AND name like '%".$name."%'",
            "code, name"
        );
        $rtn = array();
        if($type=='array'){
            return $aCode;
        }else{
            for ($i=0, $m=sizeof($aCode); $i < $m; $i++) $rtn[$aCode[$i]['code']] = $aCode[$i]['name'];
            return $rtn;
        }
    }

    /**
    +----------------------------------------------------------
    * 根据不同类型找出基础代码
    +----------------------------------------------------------
    * @param $code_type  基础代码类型
    * @param $show_type  显示类型(select, checkbox)
    * @param $show_name  显示名称
    * @param $rtn_type   返回类型(string, xml, array)
    * @param $class_name 加载样式表
    +----------------------------------------------------------
    * @access public 
    +----------------------------------------------------------
    * @return 
    +----------------------------------------------------------
    */
    public function getBaseCodeByType($code_type, $show_name="base_code", $show_type="select", $rtn_type='string', $class_name="" ) {
		$aCode = $this->pdo->find(DB_PREFIX_SYS."code_basic", "flag=1 AND type=".$code_type,  "code, name");
        
        // 要求返回数组
        if("ARRAY" == strtoupper($rtn_type)) return $aCode;
        
        $fileName = strtoupper("base_code_{$show_type}_".base64_encode($code_type)).".{$rtn_type}";
        $fileContent = "";

        if(!file_exists(WEB_ROOT.BASE_CODE_CACHE_PATH.$fileName)) {

            if("STRING" == strtoupper($rtn_type)) {
                $class_name = empty($class_name) ? "" : 'class="'. $class_name .'"';
                if("CHECKBOX" == strtoupper($show_type)){
                    foreach ($aCode as $arr) $fileContent .= '<span '. $class_name .'><input name="{show_name}" type="checkbox" value="'.$arr['code'].'" />'.$arr['name'].'</span>';
                } else if ("SELECT" == strtoupper($show_type)){
                    foreach ($aCode as $arr) $fileContent .= '<option value="'.$arr['code'].'">'.$arr['name'].'</option>';
                    $fileContent = '<select name="{show_name}" id="{show_name}" '. $class_name .'>' . $fileContent . '</select>';
                }
                Util::write_file(BASE_CODE_CACHE_PATH, $fileName, $fileContent);
                return str_ireplace("{show_name}", $show_name, $fileContent);

            } else if ("XML" == strtoupper($rtn_type)) {
                foreach ($aCode as $arr) $fileContent .= '<baseCode id="'.$arr['code'].'" text="'.$arr['name'].'"/>';
                $fileContent = '<?xml version="1.0" encoding="utf-8"?>' . $fileContent;
                Util::write_file(BASE_CODE_CACHE_PATH, $fileName, $fileContent);
                 return "/".BASE_CODE_CACHE_PATH.$fileName;
            }

        } else {
            if("STRING" == strtoupper($rtn_type)) {
                $fileContent = read_file(BASE_CODE_CACHE_PATH.$fileName);
                return str_ireplace("{show_name}", $show_name, $fileContent);
            } else if ("XML" == strtoupper($rtn_type)) { 
                return "/".BASE_CODE_CACHE_PATH.$fileName;
            }
        }
    }

    /**
     * 获取行政区域对应片区
     */
    public function getPairRegionCodeByBorough($borough_code){
        $rlt = array();
        if($borough_code) {
            $aCode = $this->pdo->find(
                DB_PREFIX_FC."region",
                "flag=1 AND borough=".$borough_code . " order by id asc",
                "region, name"
            );
            for ($i=0, $m=sizeof($aCode); $i < $m; $i++) $rlt[$aCode[$i]['region']] = $aCode[$i]['name'];
            return $rlt;
        }
        return $rlt;
    }


    /**
    +----------------------------------------------------------
    * 找出地区基础代码
    +----------------------------------------------------------
    * @param $type    类型(area: 省  city: 城市)
    * @param $select  生成选中
    +----------------------------------------------------------
    * @access public 
    +----------------------------------------------------------
    * @return 
    +----------------------------------------------------------
    */
    public function getRegion($type='area', $select="") {
        $where = "flag=1 AND type='107' ";
        $select = empty($select) ? CURRENT_REGION : $select;
        if("AREA" == strtoupper($type)) $where .= " AND SUBSTR(code, 3)='0000'";
        
        // 代码查询
		$aCode = $this->pdo->find(DB_PREFIX_SYS."code_basic", $where,  "code, name", "code");
        
        // 扩展名
        $fileExt = "CITY" == strtoupper($type) ? "xml" : "inc";
        $fileName = strtoupper("base_code_{$type}").".{$fileExt}";
        $fileContent = "";
        if(!file_exists(WEB_ROOT.BASE_CODE_CACHE_PATH.$fileName)) { // 文件不存在
            if("AREA" == strtoupper($type)) { // 省份HTML
                foreach ($aCode as $arr) {
                    if($arr['code'] == $select) {
                        $fileContent .= '<option value="'.$arr['code'].'" selected="selected">'.$arr['name'].'</option>';
                    } else { 
                        $fileContent .= '<option value="'.$arr['code'].'">'.$arr['name'].'</option>';
                    }
                }
                write_file(BASE_CODE_CACHE_PATH, $fileName, $fileContent);
                return $fileContent;
            } else if("CITY" == strtoupper($type)) { // 城市XML
                $arrXml = array();
                foreach ($aCode as $arr) {
                    $code = $arr['code'];
                    if(substr($code, 2, 4) === "0000") {
                        //$iTemp = 0;
                        $arrXml[] = '</area>';
                        $arrXml[] = '<area id="'.$code.'" text="'.$arr['name'].'">';
                    } else {
                        $arrXml[] = '<city id="'.$code.'" text="'.$arr['name'].'"/>';
                    }
                }
                $arrXml[] = '</area>';
                array_shift($arrXml);
                $fileContent = '<?xml version="1.0" encoding="utf-8"?><region>'.implode("", $arrXml)."</region>";
                write_file(BASE_CODE_CACHE_PATH, $fileName, $fileContent);
                return "/".BASE_CODE_CACHE_PATH.$fileName;
            }
        } else { // 存在
            if("AREA" == strtoupper($type)) { // 省份HTML
                return read_file(BASE_CODE_CACHE_PATH.$fileName);
            } else if("CITY" == strtoupper($type)) { // 城市XML
                return "/".BASE_CODE_CACHE_PATH.$fileName;
            }
        }
    }
	
	
    /**
    +----------------------------------------------------------
    * 找出会员类型代码
    +----------------------------------------------------------
    * @param 
    +----------------------------------------------------------
    * @access public 
    +----------------------------------------------------------
    * @return array
    +----------------------------------------------------------
    */	
	public function getUserType(){
		$aUserTypes = array("1"=>"个人会员", "2"=>"开发商会员", "3"=>"中介会员", "4"=>"经纪人", "9"=>"系统人员","11"=>"中介经纪人");
		return $aUserTypes;
	}

    /**
    +----------------------------------------------------------
    * 根据不同类型列出栏目树
    +----------------------------------------------------------
    * @param int $edit  是否生成编辑内容
    +----------------------------------------------------------
    * @access public 
    +----------------------------------------------------------
    * @return Array 栏目
    +----------------------------------------------------------
    */
	public function getTypeOfCategory($edit = false){
		$type = (int)$type;
		$aTree = $this->pdo->find("category", "flag=1 AND type=".$this->type,  "id, name, parent_id, url, target, order_list, description", "parent_id");
		$tree = new Tree($aTree, 1, $edit);
		$aHtml = $tree->getTreeXml();
		return $aHtml;
	}

    /**
    +----------------------------------------------------------
    * 保存栏目
    +----------------------------------------------------------
    * @param array $map  _POST提交上来的数据
    +----------------------------------------------------------
    * @access public 
    +----------------------------------------------------------
    * @return String 提示信息
    +----------------------------------------------------------
    */
	public function saveCategory($map){
		$name = $map['name'];
		$id  = $map['hidId'];
		$pid = $map['hidParentId'];
		
		$url = $map['url'];
		$tag = $map['target'];
		$odr = $map['order_list'];
		$des = $map['description'];
			
		$arrSave = array("name" => $name, "type" => $this->type, "url" => $url, "target" => $tag, "description" => $des );

		// 有值判断
		if(!empty($odr)) $arrSave['order_list'] = (int) $odr;

		if(empty($id)) { // 新增
			$arrSave['parent_id'] = $pid;
			$isOk = $this->pdo->add($arrSave, "category");
		} else { // 修改
			$isOk = $this->pdo->update($arrSave, "category", "id=".$id);
		}
		return ($isOk ? "保存成功" : "保存失败");
	}

}

?>